﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;

namespace WindowsPhoneMvp.Navigation
{
    public class DefaultViewFinder : IViewFinder
    {
        private readonly IEnumerable<Type> views;

        public DefaultViewFinder()
        {
            views = Application.Current.GetType().Assembly
                .GetTypes()
                .Where(t => typeof(IView).IsAssignableFrom(t));
        }

        public string ViewPath(string viewName)
        {
            var destView = viewName;
            if (destView.EndsWith("View"))
            {
                destView = destView.Substring(0, destView.LastIndexOf("View"));
            }
            return ViewPath(viewName, destView);
        }

        public string ViewPath(string viewName, string parentView)
        {
            return string.Format("/Views/{0}/{1}.xaml", parentView, viewName);
        }

        public Type FromInterface<TIView>() where TIView : IView
        {
            return views
                .Where(x => x != typeof(TIView))
                .First(t => typeof(TIView).IsAssignableFrom(t));
        }
    }
}
